const tbody = document.querySelector('tbody');

// 获取数据-渲染数据
function getscoreList() {
    axios.get('/score/list').then(result => {
        console.log(result);
        let html = '';
        const obj = result.data.data;
        for (const key in obj) {
            const tempHtml = obj[key].score.reduce((h, v, i) => h +
                `<td class="score">${v}<input type="text" data-batch="${i+1}" data-id="${key}"></td>`, '')
            html += `<tr>
            <th scope="row">${key}</th>
            <td>${obj[key].name}</td>
            ${tempHtml}
          </tr>`
        }
        tbody.innerHTML = html;
        const inputs = document.querySelectorAll('tbody input');
        inputs.forEach(input => {
            let first;
            let second;
            input.addEventListener('focus', function(e) {
                first = input.value;
            })
            input.addEventListener('blur', function(e) {
                input.style.display = 'none';
                second = input.value;
                if (first === second) {
                    return
                }
                const data = {
                    "stu_id": input.dataset.id,
                    "batch": input.dataset.batch,
                    "score": input.value,
                }
                axios.post('/score/entry', data).then(result => {
                    if (result.data.code === 0) {
                        toastr.success(result.data.message)
                        getscoreList();
                    }
                })
            })
        })
    })
}
getscoreList();

tbody.addEventListener('dblclick', function(e) {
    if (e.target.nodeName === 'TD' && e.target.classList.contains('score')) {
        const input = e.target.querySelector('input');
        input.style.display = 'block';
        input.value = e.target.innerText;
        input.focus();
    }
})